package net.zjitc.bookshop15.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.zjitc.bookshop15.pojo.User;
import net.zjitc.bookshop15.service.userService;
import net.zjitc.bookshop15.util.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 董熠涛
 * @date 2025/4/28 14:20
 */
@RestController
public class loginController {

    @Autowired
    private userService userservice;

    ApiResponse apiResponse = new ApiResponse();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/login")
    public ApiResponse login(@RequestBody User user) throws JsonProcessingException {
        String jwt = userservice.login(user);
        if (jwt == null) {
            apiResponse.error(401,"用户名或者密码错误", null);
            return apiResponse;
        }

        apiResponse.oK("Success",jwt);
        return apiResponse;
    }

    @PostMapping("/logout")
    public ApiResponse<String> logout(HttpServletRequest request, HttpServletResponse response){
        String jwt = request.getHeader("JWT");
        if (jwt == null){
            jwt = request.getParameter("JWT");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication!=null){
//            清空上下文
            new SecurityContextLogoutHandler().logout(request,response,authentication);
//            清除redis
            stringRedisTemplate.delete("token_"+jwt);
        }
        ApiResponse<String> stringApiResponse = new ApiResponse<>();
        stringApiResponse.oK("登出成功",null);
        return stringApiResponse;
    }
}
